package jdom;
import java.util.ArrayList;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class StartApp {

	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		ArrayList<String> fileNames = new ArrayList<String>();
		fileNames.add("libraries_instance1.xml");
		fileNames.add("libraries_instance2.xml");

		Software software = mergeFilesToOneSoftwareObject(fileNames);

		Document document = softwareObjectToXmlDocument(software);

		try {
			XMLOutputter out = new XMLOutputter();
			java.io.FileWriter writer = new java.io.FileWriter("result.xml");
			out.output(document, writer);
			writer.flush();
			writer.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("done");

	}

	/**
	 * 
	 * @param fileNames
	 * @return
	 */
	private static Software mergeFilesToOneSoftwareObject(
			ArrayList<String> fileNames) {
		Software result = new Software();

		for (String fileName : fileNames) {
			SAXBuilder parser = new SAXBuilder();
			try {
				Document doc = parser.build(fileName);

				XmlContentGetterUsingJdom jdom = new XmlContentGetterUsingJdom();

				// libraries
				ArrayList<Library> libraries = new ArrayList<Library>();
				libraries = jdom.getAllNewLibraries(doc, result.getLibraries());
				result.addToLibraries(libraries);

				// developers
				ArrayList<Developer> developers = new ArrayList<Developer>();
				developers = jdom.getAllNewDevelopers(doc,
						result.getDevelopers());
				result.addToDevelopers(developers);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 
	 * @param s
	 * @return
	 */
	private static Document softwareObjectToXmlDocument(Software s) {

		Element software = new Element(XmlTags.TAG_SOFTWARE);
		Element libraries = new Element(XmlTags.TAG_LIBRARIES);
		Element developers = new Element(XmlTags.TAG_DEVELOPERS);

		for (Library lib : s.getLibraries()) {
			if (lib != null) {
				Element libEl = lib.convertToXmlElement();
				libraries.addContent(libEl);
			}
		}

		for (Developer dev : s.getDevelopers()) {
			if (dev != null) {
				Element devEl = dev.convertToXmlElement();
				developers.addContent(devEl);
			}
		}

		software.addContent(libraries);
		software.addContent(developers);

		return new Document(software);

	}

}